var express = require('express');
var router = express.Router();
const multer = require('multer');
const path = require('path')
const fs = require('fs')
var { userModel, cateModel, proModel, residentModel } = require('../model/model')
// 朱炫泽 我的后端


// 设置上传目录
const uploadDir = path.join(__dirname, '../uploads');

// 确保上传目录存在
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 配置 multer
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadDir); // 指定文件保存路径
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + path.extname(file.originalname)); // 使用时间戳生成文件名
  },
});

const upload = multer({ storage: storage });

// 中间件：解析请求体中的表单数据
router.use(express.urlencoded({ extended: true }));


// 图片上传路由
router.post('/upload', upload.single('image'), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).send('请上传一张图片文件');
    }

    res.send({
      code: 200,
      msg: '上传成功',
      url: `http://localhost:3000/uploads/${req.file.filename}` // 返回可以访问的图片 URL
    });
  } catch (error) {
    console.error('上传错误:', error);
    res.status(500).send('上传失败');
  }
});



router.get('/getDataList', async (req, res) => {
  const name = req.query.name
  let arr = [{ $or:[{goods:1},{goods:2}] }]
  if (name != '') {
    arr.push({ name: new RegExp(name) })
  }

  const data = await proModel.find({ $and: arr })
  res.send({
    code: 200,
    data: data
  })
})

router.post('/updateStatus', async (req, res) => {
  await proModel.updateOne({ _id: req.body._id }, { $set: { status: req.body.status } })
  res.send({
    code: 200,
    msg: '修改成功'
  })

})
router.get('/getUseName', async (req, res) => {
  const { id } = req.query
  const data = await residentModel.findOne({ _id: id })
  console.log(data);

  res.send({
    code: 200,
    data
  })
})

router.post('/updateUseName', async (req, res) => {
  const { id, title,jifen,avater,phone} = req.body
  const arr ={
    _id:id,
    name:title,
    jifen:jifen,
    avater:avater,
    phoneNumber:phone
  }
  
  await residentModel.updateOne({_id:id},arr)
  res.send({
    code: 200,
    msg: '修改成功'
  })
})


let AlipaySdk = require('alipay-sdk').default;
let AlipaySdkForm = require('alipay-sdk/lib/form').default;
router.post('/zhifu', async (req, res) => {
  // 从请求中获取支付的金额 // 从请求中获取订单 ID
  const { id, price,name } = req.body;
  // 实例化客户端
  const alipaySdk = new AlipaySdk({
    // 设置应用 ID
    appId: '9021000142640237',
    // 支付网关
    gateway: 'https://openapi-sandbox.dl.alipaydev.com/gateway.do',
    // 设置应用私钥
    privateKey: "MIIEowIBAAKCAQEAn5qjWQyuvToLQZxf6fzpsNs++fvthCDzh0yS69bKX/+my9nvfPSlME3S5fVt1GpsN1LixqG0ybi4YCG5bzA6zOKBEisrv45UvtsNfd3UJxBj3UxuJYzopYdKU6sUzuctK6IDWQg78kNE7Re1Cg48denScffgHMV/yYbD6es7OXAE47k0pcmXwmr4YrcOtM4D8DAML6yRevwaMk9imyJXKYnWKa9Pu54rqIoPLw0XU2LFYXwoMGuSAJ5IBewBgikh7BDr91QoldfbK02d+b6drzx6113zkfVXsBDhU6v5qysSSqzRxk6srlwT4BhWB4uQlphkTaVVUVIASHSCMAOFFwIDAQABAoIBABMmI4kQm3p6l1Uk5OEXBhbBB1pI3qNmrLFD/7CqEZfY/XMhz7kHRTZ5b99FRgshRaCRokHArwcw0XY/NZdgiv2AA4phgZs3AXXwpDrAva5+Ke0oOWLp+BO8Gq/VK+bzF5lPk+U/tqmHZqKnoIH3WUuwZR5lZg8tpvpP3/uVzIJEfJJiO2SwaMogvYoDzIxk3GGpoHNaM7GvAP/M7pwkAUa2zq3W6hNwUOLv+MyuLzhVznDPOsXRrIFzwl35GiaO+BfOaol+u5JxgVROJjbJh0dvkQW2rK9FM6j6ejUwQ+zLAX1YMcmJ+zwfHR8NRt1t6tHpWZvJrl5eMjneZDoisukCgYEA4iGIFnY8mpu5XMG3B9pJ06h0DpEq0cyyxlmEjoRIAGAAC1ioj9Ri/sZSYFPeC7vMKr3sb3P+hxEoZFGIGcIokUWYPYT5D9W17DMnyXJGro+CXkJjDXjek93Z/YZwUPMt1qMNJ+qnXHKPrij++mN4/U6UprkJ2O9r+rTW5UzqurMCgYEA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52ttl5diR+LbzEZIAxoQqmKUzCmIkDQIDAQAB",
    // 密钥类型，请与生成的密钥格式保持一致，参考平台配置一节
    signType: 'RSA2',
    // 设置网关地址，默认是 https://openapi.alipay.com
    // endpoint: 'https://openapi.alipay.com',
  });
  let formData = new AlipaySdkForm();
  formData.addField('returnUrl', 'http://localhost:3001/list#/my')
  formData.addField('bizContent', {
    outTradeNo: Date.now(),
    productCode: 'FAST_INSTANT_TRADE_PAY',
    totalAmount: price.toString(),//支付金额
    subject: name,
    body: '商品详情',
  });
  try {
    const result = await alipaySdk.exec(
      'alipay.trade.wap.pay',
      {},
      { formData: formData },
    );

    // console.log(result, 'result');

    // 完成支付后，更新支付状态
    // 假设支付状态存储在某个模型中，比如 orderModel
    await residentModel.updateOne({ _id: id }, { $set: {member:true,datetime:new Date()} });

    res.send(result);
  } catch (error) {
    console.error(error);
    res.status(500).send({ code: 500, msg: '支付失败', error });
  }
})

module.exports = router;